package com.ruoyi.system.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.GwSealInfo;
import com.ruoyi.system.domain.vo.GwSealInfoVO;
import com.ruoyi.system.mapper.GwSealInfoMapper;
import com.ruoyi.system.service.IGwSealInfoService;
import com.ruoyi.system.utils.AgentUtil;
import com.tencent.essbasic.common.CreateFlowUtils;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.essbasic.v20210526.EssbasicClient;
import com.tencentcloudapi.essbasic.v20210526.models.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

import static com.tencent.essbasic.common.CreateFlowUtils.convertImageFileToBase64;

/**
 * 企业印章管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-26
 */
@Service
public class GwSealInfoServiceImpl implements IGwSealInfoService 
{
    @Resource
    private GwSealInfoMapper gwSealInfoMapper;
    @Resource
    private AgentUtil agentUtil;
    /**
     * 查询企业印章管理
     * 
     * @param id 企业印章管理主键
     * @return 企业印章管理
     */
    @Override
    public GwSealInfo selectGwSealInfoById(String id)
    {
        return gwSealInfoMapper.selectGwSealInfoById(id);
    }

    /**
     * 查询企业印章管理列表
     * 
     * @param gwSealInfo 企业印章管理
     * @return 企业印章管理
     */
    @Override
    public List<GwSealInfo> selectGwSealInfoList(GwSealInfo gwSealInfo)
    {
        if(!StringUtils.isEmpty(SecurityUtils.getLoginUser().getEnterpriseId())){
            gwSealInfo.setEnterpriseId(SecurityUtils.getLoginUser().getEnterpriseId());
        }
        gwSealInfo.setDelFlag("0");
        return gwSealInfoMapper.selectGwSealInfoList(gwSealInfo);
    }

    /**
     * 新增企业印章管理
     * 
     * @param gwSealInfo 企业印章管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertGwSealInfo(GwSealInfo gwSealInfo){
//        if(StringUtils.isBlank(gwSealInfo.getSealPhoto())){
//           return  AjaxResult.error("图片不能为空");
//        }
//        String replace = gwSealInfo.getSealPhoto().substring(15);
//        String base64 = convertImageFileToBase64(RuoYiConfig.getUploadPath() + replace);
//        System.out.println("fileBase64:"+base64);
//        if(StringUtils.isEmpty(base64)){
//            return  AjaxResult.error("图片转换base64格式失败");
//        }
//        gwSealInfo.setSealImageBase64(base64);
        //添加校验：同一个企业只能有一个公章，即印章类型为OFFICIAL的
        if(gwSealInfo!=null && gwSealInfo.getSealType()!=null && "OFFICIAL".equals(gwSealInfo.getSealType())){
            GwSealInfo old = new GwSealInfo();
            old.setEnterpriseId(SecurityUtils.getLoginUser().getEnterpriseId());
            old.setSealType(gwSealInfo.getSealType());
            List<GwSealInfo> list = gwSealInfoMapper.selectGwSealInfoList(old);
            if(!CollectionUtils.isEmpty(list)){
                return  AjaxResult.error("统一企业只允许创建一个公司章，不可重复创建！");
            }
        }


        gwSealInfo.setSealType(gwSealInfo.getSealType());
        //接入电子签的创建印章接口
        EssbasicClient client = CreateFlowUtils.initClient();
        // 实例化一个请求对象,每个接口都会对应一个request对象
        CreateSealByImageRequest req = new CreateSealByImageRequest();
        req.setAgent(agentUtil.setAgent());
        req.setSealName(gwSealInfo.getSealName());
        req.setGenerateSource("SealGenerateSourceSystem");

//        req.setSealImage(gwSealInfo.getSealImageBase64());

        CreateSealByImageResponse response = null;
        try {
            response = client.CreateSealByImage(req);
        } catch (TencentCloudSDKException e) {
            return  AjaxResult.error("存在审核中或审核通过的同名印章，需更换印章名称");
        }

        if(response!=null){
            gwSealInfo.setSealId(response.getSealId());
        }
        gwSealInfo.setCreateBy(SecurityUtils.getUserId()+"");
        gwSealInfo.setEnterpriseId(SecurityUtils.getLoginUser().getEnterpriseId());
        gwSealInfo.setCreateTime(DateUtils.getNowDate());
        gwSealInfo.setUpdateBy(SecurityUtils.getUserId()+"");
        gwSealInfo.setUpdateTime(DateUtils.getNowDate());
        gwSealInfo.setId(IdUtils.fastSimpleUUID());
        gwSealInfoMapper.insertGwSealInfo(gwSealInfo);
        return AjaxResult.success();
    }

    /**
     * 修改企业印章管理
     * 
     * @param gwSealInfo 企业印章管理
     * @return 结果
     */
    @Override
    public int updateGwSealInfo(GwSealInfo gwSealInfo)
    {
        gwSealInfo.setUpdateTime(DateUtils.getNowDate());
        return gwSealInfoMapper.updateGwSealInfo(gwSealInfo);
    }

    /**
     * 批量删除企业印章管理
     * 
     * @param ids 需要删除的企业印章管理主键
     * @return 结果
     */
    @Override
    public int deleteGwSealInfoByIds(String[] ids) throws TencentCloudSDKException {
        int num = 0;
        for(String  id: ids){
            GwSealInfo gwSealInfo =  gwSealInfoMapper.selectGwSealInfoById(id);
            EssbasicClient client = CreateFlowUtils.initClient();
            //实例化一个请求对象,每个接口都会对应一个request对象
            ChannelUpdateSealStatusRequest req = new ChannelUpdateSealStatusRequest();
            req.setAgent(agentUtil.setAgent());
            req.setStatus("DISABLE");
            req.setSealId(gwSealInfo.getSealId());
            client.ChannelUpdateSealStatus(req);

            gwSealInfo.setDelFlag("1");
            num = num+gwSealInfoMapper.deleteGwSealInfoById(id);
        }

        return num;
    }

    /**
     * 删除企业印章管理信息
     * 
     * @param id 企业印章管理主键
     * @return 结果
     */
    @Override
    public int deleteGwSealInfoById(String id)
    {
        return gwSealInfoMapper.deleteGwSealInfoById(id);
    }

    @Override
    public List<GwSealInfoVO> selectList(GwSealInfo gwSealInfo) {
        if(!StringUtils.isEmpty(SecurityUtils.getLoginUser().getEnterpriseId())){
            gwSealInfo.setEnterpriseId(SecurityUtils.getLoginUser().getEnterpriseId());
        }
        gwSealInfo.setDelFlag("0");
        return gwSealInfoMapper.selectList(gwSealInfo);
    }

    @Override
    public AjaxResult getSealUrl(GwSealInfo gwSealInfo) throws TencentCloudSDKException {
        if(gwSealInfo==null || StringUtils.isBlank(gwSealInfo.getId())){
            return AjaxResult.error("印章ID为空");
        }
        gwSealInfo = gwSealInfoMapper.selectGwSealInfoById(gwSealInfo.getId());
        if(StringUtils.isBlank(gwSealInfo.getSealId())){
            return AjaxResult.error("未查询到电子签关联印章");
        }
        // 实例化一个client
        EssbasicClient client = CreateFlowUtils.initClient();
        // 实例化一个请求对象,每个接口都会对应一个request对象
        ChannelDescribeOrganizationSealsRequest req = new ChannelDescribeOrganizationSealsRequest();

        req.setAgent(agentUtil.setAgent());

        req.setSealId(gwSealInfo.getSealId());

        req.setLimit(100L);

        req.setOffset(0L);

        // 返回的resp是一个ChannelDescribeOrganizationSealsResponse的实例，与请求对象对应
        ChannelDescribeOrganizationSealsResponse response = client.ChannelDescribeOrganizationSeals(req);
        if(response!=null && response.getSeals().length>0){
            return AjaxResult.success(response.getSeals()[0].getUrl());
        }
        return AjaxResult.error("未查询到关联的电子签印章");
    }
}
